package com.example.design.a.singleton;

import java.util.UUID;

/**
 * 单例模式
 * 假装这是一个数据库连接类
 */
public class MyConnection {

    private boolean connect;
    private String name;

    /**
     * 私有化构造方法
     * 不允许外界调用, 从而实例对象
     */
    private MyConnection() {
        this.connect = true;
        this.name = "连接 = " + UUID.randomUUID();
    }

    /**
     * 定义静态变量
     * volatile 关键词屏蔽jvm优化可能出现的指令重排
     */
    private volatile static MyConnection myConnection = new MyConnection();

    /**
     * 判断当前连接是否打开
     *
     * @return
     */
    public boolean isConnect() {
        return connect;
    }

    /**
     * 连接
     */
    public void connect() {
        this.connect = true;
    }

    /**
     * 关闭连接
     */
    public void close() {
        this.connect = false;
    }

    /**
     * 懒汉式
     *
     * @return
     */
    public static synchronized MyConnection getConnection() {
        if (myConnection == null) {
            myConnection = new MyConnection();
        }
        return myConnection;
    }

    /**
     * 饿汉式
     *
     * @return
     */
/*    public static MyConnection getConnection() {
        return myConnection;
    }*/

    /* ***************** Getter And Setter start ***************** */
    public boolean getConnect() {
        return connect;
    }

    public void setConnect(boolean connect) {
        this.connect = connect;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    /* ***************** Getter And Setter end ***************** */

    @Override
    public String toString() {
        return "MyConnection{" +
                "connect=" + connect +
                ", name='" + name + '\'' +
                '}';
    }
}
